%%%-------------------------------------------------------------------
%%% @author wukai
%%% @copyright (C) 2017, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 22. 十二月 2017 09:03
%%%-------------------------------------------------------------------
-module(publish_frame).
-author("wukai").
-include("include/mqtt_protocol.hrl").
-record(publish,{from,topic,t_len,content,dup,qos,retain}).
%% API
-export([wrap/7]).
-export([enc_bin/2]).
-export([qos/1]).
-export([wrap_dispatch/2]).
-export([topic/1]).
-export([content/1]).


wrap(Client,TN, TLen, Con,Dup, Qos, Retain)->
#publish{from = Client,topic =TN,t_len = TLen,dup = Dup, content = Con,qos = Qos,retain = Retain }.


enc_bin(P,PacketId) when P#publish.qos>0->
#publish{from = _,topic =T,t_len = TLen,dup = Dup,
  content = Con,qos = Qos,retain = Retain}=P,
  CLen = byte_size(Con),
  ReLen = protocol_util:len_bytes(2 + TLen + 2 + CLen),
  <<?FRAME_PUB:4, Dup:1, Qos:2, Retain:1, ReLen/binary, TLen:16/big, T/binary, PacketId:16/big, Con/binary
  >>;

enc_bin(P,_)->
  #publish{from = _,topic =T,t_len = TLen,dup = Dup,
    content = Con,qos = Qos,retain = Retain}=P,
  CLen = byte_size(Con),
  ReLen = protocol_util:len_bytes(2 + TLen + CLen),
  <<?FRAME_PUB:4, Dup:1, Qos:2, Retain:1, ReLen/binary, TLen:16/big, T/binary, Con/binary>>.

qos(P)->P#publish.qos.
wrap_dispatch(P,Qos)->P#publish{qos = Qos}.
topic(P)->P#publish.topic.
content(P)->P#publish.content.